<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="orderSnId">
        <el-input
          v-model="queryParams.orderSnId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="服务类型" prop="serviceId">
        <el-select v-model="queryParams.serviceId" placeholder="请选择服务类型">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in managerList"
            :key="index"
            :label="item.typeName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="是否加急" prop="urgent">
        <el-select v-model="queryParams.urgent" placeholder="请选择">
          <el-option
            v-for="(item, index) in urgent"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="请选择订单状态"
        >
          <el-option
            v-for="(item, index) in orderStatus"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="serviceStatus">
        <el-select
          v-model="queryParams.serviceStatus"
          placeholder="请选择服务状态"
        >
          <el-option
            v-for="(item, index) in serviceStatus"
            :key="index"
            :label="item"
            :value="index"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处理人" prop="processedName">
        <el-input
          v-model="queryParams.processedName"
          placeholder="请输入处理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="处理日期" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          align="right"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--             
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['order:order:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-tabs v-model="tabName" @tab-click="tabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待定价" name="awaitingQuote"></el-tab-pane>
      <el-tab-pane label="待支付" name="awaitingPayment"></el-tab-pane>
      <el-tab-pane label="处理中" name="inProgress"></el-tab-pane>
      <el-tab-pane label="待审核" name="awaitingApproval"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
    </el-tabs>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="订单编号" align="center" prop="orderSnId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="服务类型" align="center" prop="serviceId">
        <template slot-scope="scope">
          {{ scope.row.serviceName || serviceTypeComputed(scope.row.serviceId) }}
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" />
      <!-- <el-table-column label="是否加急" align="center">
        <template slot-scope="scope">
          <el-tag type="success">{{ urgent[scope.row.urgent] }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="订单状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success">{{
            orderStatus[scope.row.orderStatus]
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="服务状态" align="center">
        <template slot-scope="scope">
          {{ serviceStatus[scope.row.serviceStatus] }}
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="processedName" />
      <el-table-column label="处理日期" align="center" prop="parseTime" />
      <el-table-column label="科藤备注" align="center" prop="ktRemarks" width="140">
        <template slot-scope="scope">
          <div class="remarks" @click="bzChange(scope.$index, scope.row)">
            {{ scope.row.ktRemark? scope.row.ktRemark.slice(0, 6): '' }}
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="价格" align="center" prop="servicePrice" /> -->

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- 报价/修改报价 -->
          <el-button
            v-if="[0, 1].includes(scope.row.orderStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="quotation(scope.$index, scope.row)"
            v-hasPermi="['order:price:quotation']"
            >{{ priceLabel[scope.row.orderStatus] }}</el-button
          >

          <!-- 审核 -->
          <el-button
            v-if="8 == scope.row.orderStatus"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddAudit(scope.row, scope.$index)"
            v-hasPermi="['order:detail']"
            >审核</el-button
          >
          <!-- 完工确认 -->
          <el-button
            v-if="[6].includes(scope.row.orderStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOrderConfirm(scope.row, scope.$index)"
            v-hasPermi="['order:detail']"
            >完工确认</el-button
          >
          <!-- 驳回 -->
          <el-button
            v-if="[6].includes(scope.row.orderStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOrderReject(scope.row, scope.$index)"
            v-hasPermi="['order:detail']"
            >驳回</el-button
          >
          <!-- 派稿 -->
          <el-button
            v-if="[5].includes(scope.row.orderStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dispatcherProcessd(scope.row, scope.$index)"
            v-hasPermi="['order:detail']"
            >派稿</el-button
          >
          <!-- 查看详情 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:detail']"
            >查看详情</el-button
          >

          <!-- 取消订单 -->
          <el-button
            v-if="[2, 3].includes(scope.row.orderStatus)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOrderCancel(scope.row, scope.$index)"
            v-hasPermi="['order:detail']"
            >取消订单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <qutation
      v-if="visible"
      secondLabel="报价金额"
      placeholder="请输入报价金额"
      :visible="visible"
      editKey="servicePrice"
      @close="closeDialog"
      @receiveData="receiveData"
      :qutationData="selectionRow"
    />
    <dispatcher
      v-if="dispatcherVisible"
      @close="closeDispatcherDialog"
      @receiveData="receiveAssignData"
      :order="selectionRow"
      :visible="dispatcherVisible"
    ></dispatcher>

    <el-dialog
      title="驳回编辑"
      :visible.sync="rejectFormVisible"
      destroy-on-close
    >
      <el-form
        ref="rejectForm"
        :model="rejectForm"
        :rules="rejectFormRules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="订单编号" prop="orderSnId">
          <el-input v-model="rejectForm.orderSnId" disabled></el-input>
        </el-form-item>
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="2"
            placeholder="请输入驳回原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrderReject">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 备注弹窗 -->
    <desc-dialog
      :visible="bzVisible"
      title="科藤备注"
      twiceLabel="科藤备注"
      :id="bzForm.id"
      :desc="bzForm.content"
      :orderId="bzForm.orderId"
      @cancel="bzVisible = false"
      @confirm="updateKtRemark"
    ></desc-dialog>
  </div>
</template>

<script>
import {
  delOrder,
  addOrder,
  updateOrder,
  ktRemark,
  cancelOrder,
  confirmOrder,
  rejectOrder,
} from "@/api/order/order";
import { listManager } from "@/api/service-manager/manager";
import {
  ARRERS,
  ORDERS_MOUDLE_TATUSES,
  PRICE_WORD_LABEL,
  SERVICE_STATUS,
} from "@/constant/const";
import { timestampToDate } from "@/utils/time";
import { OrderComponentList } from "../../jscomponent/order.component.js";
import { Message } from "element-ui";
export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      tabName: "all",
      // 选中数组
      ids: [],
      priceLabel: PRICE_WORD_LABEL,
      urgent: ARRERS,
      orderStatus: ORDERS_MOUDLE_TATUSES,
      serviceStatus: SERVICE_STATUS,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      visible: false,
      dispatcherVisible: false, // 派稿弹窗
      selectionRow: {},
      selectionIndex: 0,
      // 弹出层标题
      // 是否显示弹出层
      dateRange: [],
      /**
       * @param {OrderComponentList} orderComponentList
       */
      orderComponentList: undefined,

      // 实例
      instanceName: "getList",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSnId: null,
        userName: null,
        userId: null,
        serviceId: null,
        urgent: null,
        orderStatus: null,
        parse_time: null,
        processedName: null,
        serviceStatus: null
      },
      managerList: [],
      isSearch: false,
      rejectForm: {
        id: "",
        reason: "",
        orderSnId: "",
      },
      rejectFormVisible: false,
      rejectFormRules: {
        reason: [
          { required: true, message: "请输入驳回原因", trigger: "blur" },
        ],
      },
      bzVisible: false, // 备注弹窗
      bzForm: {
        // 备注表单
        id: "",
        content: "",
        orderId: "",
        ind: 0,
      },
    };
  },

  components: {
    qutation: () => import("./component/commomEditValue.vue"),
    dispatcher: () => import("./component/dispatcher.vue"),
    descDialog: () => import("@/components/descDialog"),
  },

  created() {
    listManager({
      pageNum: 1,
    }).then((response) => {
      this.managerList = response.rows;

      sessionStorage.setItem("managerList", JSON.stringify(this.managerList));
    });
  },

  mounted() {
    this.orderComponentList = new OrderComponentList(this);

    this.orderComponentList.getList();
  },
  methods: {
    /**
     * 驳回
     */
    handleOrderReject(ite, ind) {
      this.rejectForm.id = ite.id;
      this.rejectForm.orderSnId = ite.orderSnId;
      this.rejectFormVisible = true;
    },

    submitOrderReject() {
      this.$refs["rejectForm"].validate().then((result) => {
        if (!result) return;
        rejectOrder(this.rejectForm).then((res) => {
          Message.success("驳回成功");
          this.rejectFormVisible = false;
          this.getList();
        });
      });
    },

    /**
     * 取消订单
     */
    handleOrderCancel(item) {
      this.$confirm("确定要取消该订单吗?", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        cancelOrder(item.id).then((res) => {
          Message.success("取消成功");
          this.getList();
        });
      });
    },

    //完工确认
    handleOrderConfirm(item) {
      this.$confirm("确定编辑已完成订单处理吗?", "完工提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        confirmOrder(item.id).then((res) => {
          Message.success("操作成功");
          this.getList();
        });
      });
    },

    receiveAssignData(data) {
      console.log("this.selectionIndex", this.selectionIndex);
      this.orderList[this.selectionIndex].orderStatus = 4;
      this.getList();
    },

    /**
     * 派工
     */
    dispatcherProcessd(orderItem, index) {
      this.dispatcherVisible = true;
      this.selectionIndex = index;
      this.selectionRow = orderItem;
    },

    getList() {
      let method = OrderComponentList.prototype[this.instanceName];
      if (!method) {
        return;
      }
      method.apply(this.orderComponentList);
    },

    tabClick(instance, tab) {
      console.log("instance.name", instance, "tab", tab);
      /**
       * @param {Function} method
       */
      this.queryParams.pageNum = 1;
      this.isSearch = false;
      this.instanceName = instance.name;

      let method = OrderComponentList.prototype[instance.name];
      if (!method) {
        return;
      }
      method.apply(this.orderComponentList);
    },

    /**
     * 接收子组件数据
     * @param {{}} orderItem
     */
    receiveData(orderItem) {
      console.log(orderItem, this.selectionIndex);
      this.orderList[this.selectionIndex].servicePrice = orderItem.servicePrice;
      this.orderList[this.selectionIndex].serviceStatus = 1;
      this.getList();
    },

    /**
     * 更新科腾备注
     * @param {number} index
     * @param {{}} row
     */
    bzChange(index, row) {
      this.bzForm.id = row.id;
      this.bzForm.orderId = row.orderSnId;
      this.bzForm.content = row.ktRemark;
      this.bzForm.ind = index;
      this.bzVisible = true;
    },

    updateKtRemark(id, content) {
      this.bzVisible = false;
      let param = {
        id: id,
        ktRemark: content,
      };
      ktRemark(param).then((response) => {
        this.orderList[this.bzForm.ind].ktRemark = content;
        this.$message.success(response.msg);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /**
     *
     * @param {number} index
     * @param {{}} row
     */
    quotation(index, row) {
      this.visible = true;
      this.selectionIndex = index;
      this.selectionRow = row;
    },

    closeDialog(value) {
      this.visible = value;
    },

    closeDispatcherDialog(value) {
      this.dispatcherVisible = value;
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderSnId: null,
        priceSum: null,
        serviceType: null,
        wordSize: null,
        userId: null,
        targetJournal: null,
        payTime: null,
        overTime: null,
        orderStatus: null,
        commentStatus: null,
        languageServiceId: null,
        payType: null,
        remarks: null,
        status: null,
        translate: null,
        urgent: null,
        platform: null,
        orderType: null,
        couponDeductible: null,
        professionalField: null,
        article: null,
        format: null,
        createTime: null,
        payManagerId: null,
        recommendNumber: null,
        teamId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.tabName = "all";
      this.queryParams.pageNum = 1;
      this.instanceName = "getList";
      this.isSearch = true;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.isSearch = false;
      this.dateRange = [];
      this.tabName = "all";
      this.instanceName = "getList";
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 查看详情 */
    handleUpdate(row) {
      sessionStorage.setItem("orderItem", JSON.stringify(row));

      this.$router.push({ path: `/order/detail/${row.id}` });
    },
    // 点击审核按钮
    handleAddAudit(row) {
      sessionStorage.setItem(
        "isAudit",
        JSON.stringify({
          id: row.id,
          isAudit: true,
        })
      );
      this.handleUpdate(row);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "order/order/export",
        {
          ...this.queryParams,
          ids: this.ids.length ? this.ids : undefined,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
  computed: {
    serviceTypeComputed() {
      return (id) => {
        if (!id) return "";
        let type = this.managerList.find((item) => item.id === id);
        return type ? type.typeName : "";
      };
    },
  },
};
</script>

<style scoped>
.remarks {
  width: 120px;
  height: 40px;
  border: 1px solid #ccc;
  cursor: pointer;
  border-radius: 6px;
  text-align: center;
  line-height: 40px;
}
.remarks:hover {
  border-color: blue;
}
</style>
